package com.jytc.framework.bo.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jytc.framework.bo.FwRoleBO;
import com.jytc.framework.bo.FwUserBO;
import com.jytc.framework.commons.Page;
import com.jytc.framework.commons.PropertyFilter;
import com.jytc.framework.commons.PropertyFilter.MatchType;
import com.jytc.framework.constants.CommonConstants;
import com.jytc.framework.constants.ResultConstants;
import com.jytc.framework.dao.FwDeptDAO;
import com.jytc.framework.dao.FwRoleDAO;
import com.jytc.framework.dao.FwRolePermissionDAO;
import com.jytc.framework.dto.FwRoleDTO;
import com.jytc.framework.po.FwDept;
import com.jytc.framework.po.FwPermission;
import com.jytc.framework.po.FwRole;
import com.jytc.framework.po.FwRolePermission;
import com.jytc.framework.po.FwUser;

/**
 * @title: FSysRoleBOImpl.java
 * @description: 角色管理业务处理类
 * 
 * @author: dongyuese
 *
 */
@Service
public class FwRoleBOImpl implements FwRoleBO
{
	/**
	 * 角色信息数据访问对象
	 */
	@Autowired
	private FwRoleDAO fwRoleDAO;

	/**
	 * 单位信息数据访问对象
	 */
	@Autowired
	private FwDeptDAO fwDeptDAO;

	/**
	 * 角色权限关系信息数据访问对象
	 */
	@Autowired
	private FwRolePermissionDAO fwRolePermissionDAO;

	/**
	 * 用户信息业务操作对象
	 */
	@Autowired
	private FwUserBO fwUserBO;

	/**
	 * 保存角色信息
	 * @param sysRoleDTO　角色信息数据传输对象
	 * @return　保存成功或失败
	 * @throws Exception
	 */
	@Transactional(readOnly = false, rollbackFor = Throwable.class)
	public int save(FwRoleDTO fwRoleDTO) throws Exception
	{
		FwRole fwRole = new FwRole();
		BeanUtils.copyProperties(fwRole, fwRoleDTO);

		//判断是否已经存在同名角色
		if (fwRoleDAO.findUnique("roleName", fwRoleDTO.getRoleName()) == null)
		{
			//保存角色信息
			fwRoleDAO.save(fwRole);

			//保存角色权限关联信息
			this.saveRolePermission(fwRoleDTO.getPermissions(), fwRole);
			return ResultConstants.INSERT_SUCCEED;
		}
		return ResultConstants.INSERT_FAILED;
	}

	/**
	 * 根据角色ID获取角色信息
	 * @param roleId　角色ID
	 * @return　角色信息实体对象
	 * @throws Exception
	 */
	public FwRole findById(Integer roleId) throws Exception
	{
		return fwRoleDAO.findById(roleId);
	}

	/**
	 * 根据角色ID删除角色信息
	 * @param roleId　角色ID
	 * @return　删除成功或失败
	 * @throws Exception
	 */
	@Transactional(readOnly = false, rollbackFor = Throwable.class)
	public int deleteById(Integer roleId) throws Exception
	{
		//有用户引用的单位不能被删除
		if (!this.validationRole(roleId))
		{
			//删除角色信息
			fwRoleDAO.deleteById(roleId);
			return ResultConstants.DELETE_SUCCEED;
		} else
		{
			return CommonConstants.ROLE_USER_QUOTED;
		}
	}

	/**
	 * 按照条件分页查询角色信息
	 * @param page　分页信息
	 * @param filters　过滤条件列表
	 * @return　角色信息集合
	 * @throws Exception
	 */
	public Page query(Page page, List<PropertyFilter> filters) throws Exception
	{
		Page pageTemp = fwRoleDAO.findByPage(page, filters);
		List tempList = pageTemp.getResult();
		List resultList = new ArrayList();
		if (tempList != null)
		{
			FwRole fwRole = null;
			FwDept tempDept = null;
			for (int i = 0; i < tempList.size(); i++)
			{
				fwRole = (FwRole) tempList.get(i);
				FwRoleDTO fwRoleDTO = new FwRoleDTO();
				BeanUtils.copyProperties(fwRoleDTO, fwRole);
				tempDept = fwDeptDAO.findById(fwRole.getDeptId());
				fwRoleDTO.setCorpName(tempDept.getDeptName());
				resultList.add(fwRoleDTO);
			}
		}
		pageTemp.setResult(resultList);
		return pageTemp;
	}

	/**
	 * 验证角色是否被用户引用，被引用返回true，否则返回false
	 * @param roleId 角色ID
	 * @return
	 * @throws Exception
	 */
	private boolean validationRole(Integer roleId) throws Exception
	{
		List<FwUser> fwLoginList = fwUserBO.queryByRoleId(roleId);
		if ((fwLoginList == null) || (fwLoginList.isEmpty()))
		{
			return false;
		}
		return true;
	}

	/**
	 * 批量删除角色信息
	 * @param roleId　角色ID集合
	 * @return 删除成功或失败
	 * @throws Exception
	 */
	@Transactional(readOnly = false, rollbackFor = Throwable.class)
	public int deleteByIds(Integer[] roleIds) throws Exception
	{
		for (Integer roleId : roleIds)
		{
			//有用户引用的单位不能被删除
			if (!this.validationRole(roleId))
			{
				//删除角色信息
				fwRoleDAO.deleteById(roleId);
			}
		}
		return ResultConstants.DELETE_SUCCEED;
	}

	/**
	 * 角色信息修改
	 * @param sysRoleDTO　角色信息数据传输对象
	 * @return
	 * @throws Exception
	 */
	@Transactional(readOnly = false, rollbackFor = Throwable.class)
	public int update(FwRoleDTO fwRoleDTO) throws Exception
	{
		//修改后的角色名是否跟原有的角色名存在重复
		FwRole fwRoleTemp = fwRoleDAO.findUnique("roleName", fwRoleDTO.getRoleName());
		if ((fwRoleTemp != null) && (fwRoleTemp.getRoleId().longValue() != fwRoleDTO.getRoleId().longValue()))
		{
			return CommonConstants.ROLE_IS_EXIST;
		}

		//如果将角色修改为无效状态，则需要判断该角色是否被用户引用，已经引用则不能修改为无效
		if ((CommonConstants.ROLE_STATUS_0 == fwRoleDTO.getStatus()) && (this.validationRole(fwRoleDTO.getRoleId())))
		{
			return CommonConstants.ROLE_USER_QUOTED;
		}

		if (fwRoleTemp == null)
		{
			fwRoleTemp = fwRoleDAO.findById(fwRoleDTO.getRoleId());
		}

		//先删除角色权限关联信息
		fwRoleTemp.getFwRolePermissions().remove(fwRoleTemp);

		//保存角色权限关联信息
		this.saveRolePermission(fwRoleDTO.getPermissions(), fwRoleTemp);

		//更新角色信息
		fwRoleTemp.setRoleDesc(fwRoleDTO.getRoleDesc());
		fwRoleTemp.setRoleName(fwRoleDTO.getRoleName());
		fwRoleTemp.setStatus(fwRoleDTO.getStatus());
		fwRoleDAO.update(fwRoleTemp);
		return ResultConstants.UPDATE_SUCCEED;
	}

	/**
	 * 保存角色权限关联信息
	 * @param permissionIds　权限ID，以逗号分隔
	 * @param sysRole 角色信息
	 */
	private void saveRolePermission(String permissionIds, FwRole fwRole)
	{
		//批量保存角色权限关联信息
		String[] permissionArr = permissionIds.split(CommonConstants.SPLIT_SYMBOL_COMMA);
		List<FwRolePermission> fwPermissionList = new ArrayList<FwRolePermission>();
		for (String permissionId : permissionArr)
		{
			FwRolePermission rolePermission = new FwRolePermission();
			rolePermission.setFwRole(fwRole);
			rolePermission.setFwPermission(new FwPermission(Integer.valueOf(permissionId)));

			//角色权限关联信息表中状态字段为预留，先默认为0，无实际意义
			rolePermission.setStatus(Integer.valueOf(0));
			fwPermissionList.add(rolePermission);
		}
		fwRolePermissionDAO.saveAll(fwPermissionList);
	}

	/**
	 * 根据单位ID查询角色信息
	 * @param corpId　单位ID
	 * @param status　角色有效标志位
	 * @return　角色信息集合
	 * @throws Exception
	 */
	public List<FwRole> findByCorpAndStatus(Integer corpId, Integer status) throws Exception
	{
		List<PropertyFilter> filterList = new ArrayList<PropertyFilter>();
		filterList.add(new PropertyFilter(MatchType.EQ + "_corpId", corpId));

		//如果validTag不为空，则添加是否有效过滤条件
		if (status != null)
		{
			filterList.add(new PropertyFilter(MatchType.EQ + "_status", status));
		}
		return fwRoleDAO.findByFilters(filterList);
	}
}
